React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
Wait for setState to Finish Before Triggering a Function
We can wait for setState
to finish before triggering a function by passing in a function as a 2nd argument of setState
.
For instance, we can write:
this.setState({
firstName,
lastName,
age
}, () => {
console.log(this.state) ;
})
We called setState
with the object with the states first.
Then we run our callback to get the latest value of this.state
.
External Link with React Router
We can add an external link by passing in a component to redirect to an external link.
For instance, we can write:
<Route path='/external-site' >
{() => {
useEffect(() => {
window.location.href = 'https://example.com';
}, [])
return null;
}}
</Route>
We used the Router
component with the path
prop to set the path.
Then in our component, we redirect to an external URL by setting the URL as the value of window.location.href
.
And we return null
to render nothing.
We can also redirect directly in componentDidMount
:
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('http://www.example.com')
}
render(){
return null;
}
}
Access a Hover State in React
We can set the hove state by listening to the mouseenter
and mouseleave
events.
For instance, we can write:
<div
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
>
foo
</div>
We can pass in event handlers to the onMouseEnter
and onMouseLeave
props.
Then we can run code within those methods to set the hover state.
PropTypes in Functional Stateless Component
We can set the prop types in the functional stateless component.
For instance, we can write:
import React from "react";
import PropTypes from "prop-types";
const Name = ({ name }) => <div>hi {name}</div>;
Name.propTypes = {
name: PropTypes.string
};
Name.defaultProps = {
name: "james"
};
We created the Name
component with the propTypes
property.
Then we set the data type of the name
prop with it.
We can also set the default value for the name
prop.
We’ve to install the propt-types
package to set types for the props.
setTimeout() in React Components
We can use setTimeout
in React components by calling setTimeout
in componentDidMount
and then clearing the timer within the componentWillMount
method.
For instance, we can write:
class App extends React.Component {
constructor() {
this.state = { position: 0, timer: undefined };
}
componentDidMount() {
const timer = setTimeout(() => this.setState({ position: 1 }), 3000)
this.setState({ timer });
}
componentWillUnmount(){
clearTimeout(this.state.timer);
};
render() {
return (
<div>
{this.state.position}
</div>
);
}
}
We called setTimeout
with a callback with the timeout time span in componentDidMount
to get the timer when the component loads.
It returns a timer object that we can call clearTimeout
with to clear the resources for the timer when the component unmounts./
We have the timer
state to set the timer returned from setTimeout
to the state.
Then we in componentWillUnmount
, we call clearTimeout
to clear the timer.
setInterval in a React Component
Like with setTimeout
, we can call setInterval
within a React component.
It’s pretty much the same as setTimeout
except that we can setInterval
and clerInterval
.
For instance, we write:
class App extends React.Component {
constructor() {
this.state = { position: 0, timer: undefined };
}
componentDidMount() {
const timer = setInterval(() => this.setState(state => ({ position: state.position + 1 })), 3000)
this.setState({ timer });
}
componentWillUnmount(){
clearInterval(this.state.timer);
};
render() {
return (
<div>
{this.state.position}
</div>
);
}
}
We called setInterval
in componentDidMount
to create a timer to run code periodically.
In the setInterval
callback, we update the position
state every 3 seconds.
Then in componentWillUnmount
, we call clearInterval
to clear the timer.
With function components, we can do the same thing.
For instance, we can write:
import React, { useState, useEffect } from 'react';
const App = () => {
const [position, setPosition] = useState(0);
const timer = () => setPosition(position => position + 1);
useEffect(() => {
const timer = setInterval(timer, 1000);
return () => clearInterval(timer);
}, []);
return <div>{position}</div>;
};
We have the useState
hook to update the position
state with setPosiitin
.
Then we have the useEffect
hook to create a timer when the component loads.
Then function we return in the useEffect
callback removes the timer with clearInterval
.
The empty array in the 2nd argument ensures that the useEffect
callback only runs when App
first loads.
Conclusion
We can create a component to redirect to an external URL.
Also, we can use setTimeout
and setInterval
in our components.
To set prop types, we can use the prop-types
package.